package com.zygh.questionnairesurvey.aop;


import cn.hutool.core.date.DateUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.zygh.questionnairesurvey.entity.Operation;
import com.zygh.questionnairesurvey.mapper.OperationMapper;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wxh
 */
@Component
@Aspect
public class LogAspect {

    @Resource
    private OperationMapper operationMapper;

    private final static Log log = LogFactory.get();

    @Pointcut("execution(* com.zygh.questionnairesurvey.controller..*(..))" +
            " && !execution(* com.zygh.questionnairesurvey.controller.LoginController..*(..))" +
            " && !execution(* com.zygh.questionnairesurvey.controller.ExportExcelController..*(..))")
    public void requestServer() {
    }

    @Around("requestServer()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        Object result = proceedingJoinPoint.proceed();

        Operation operation = new Operation();
        if(StringUtils.isNotBlank(request.getHeader("user"))){
            operation.setUserName(URLDecoder.decode(request.getHeader("user"), "utf-8"));
        }
        //获取请求ip
        operation.setIp(request.getRemoteAddr());
        //获取请求路径
        operation.setUrl(request.getRequestURL().toString());
        //获取请求方式
        operation.setHttpMethod(request.getMethod());
        //获取请求的类方法
        operation.setClassMethod(String.format("%s.%s", proceedingJoinPoint.getSignature().getDeclaringTypeName(),
                proceedingJoinPoint.getSignature().getName()));
        //获取请求参数
        operation.setRequestParams(JSON.toJSONString(getRequestParamsByProceedingJoinPoint(proceedingJoinPoint)));
        //获取返回结果
        operation.setResult(JSON.toJSONString(result));
        //获取执行时间
        operation.setTimeCost(System.currentTimeMillis() - start);
        operation.setTime(DateUtil.parse(DateUtil.now()));
        //log.info("Request Info      : {}", JSON.toJSON(operation));

        operationMapper.insert(operation);
        return result;
    }


    @AfterThrowing(pointcut = "requestServer()", throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, RuntimeException e) throws UnsupportedEncodingException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Operation operation = new Operation();
        if(StringUtils.isNotBlank(request.getHeader("user"))){
            operation.setUserName(URLDecoder.decode(request.getHeader("user"), "utf-8"));
        }
        //获取请求ip
        operation.setIp(request.getRemoteAddr());
        //获取请求路径
        operation.setUrl(request.getRequestURL().toString());
        //获取请求方式
        operation.setHttpMethod(request.getMethod());
        //获取请求的类方法
        operation.setClassMethod(String.format("%s.%s", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName()));
        //获取请求参数
        operation.setRequestParams(JSON.toJSONString(getRequestParamsByJoinPoint(joinPoint)));
        //获取异常信息
        operation.setException(e.getMessage());
        operation.setTime(DateUtil.parse(DateUtil.now()));
        //log.error("Error Request Info      : {}", JSON.toJSON(operation));
        operationMapper.insert(operation);
        //log.error(e);
    }

    /**
     * 环绕通知获取入参
     *
     * @param proceedingJoinPoint 连接点
     * @return 参数集合
     */
    private Map<String, Object> getRequestParamsByProceedingJoinPoint(ProceedingJoinPoint proceedingJoinPoint) {
        //参数名
        String[] paramNames = ((MethodSignature) proceedingJoinPoint.getSignature()).getParameterNames();
        //参数值
        Object[] paramValues = proceedingJoinPoint.getArgs();

        return buildRequestParam(paramNames, paramValues);
    }

    /**
     * 异常通知获取入参
     *
     * @param joinPoint 连接点
     * @return 参数集合
     */
    private Map<String, Object> getRequestParamsByJoinPoint(JoinPoint joinPoint) {
        //参数名
        String[] paramNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        //参数值
        Object[] paramValues = joinPoint.getArgs();

        return buildRequestParam(paramNames, paramValues);
    }

    /**
     * 处理请求参数
     *
     * @param paramNames  参数名
     * @param paramValues 参数值
     * @return 参数集合
     */
    private Map<String, Object> buildRequestParam(String[] paramNames, Object[] paramValues) {
        Map<String, Object> requestParams = new HashMap<>(8);
        for (int i = 0; i < paramNames.length; i++) {
            Object value = paramValues[i];

            //如果是文件对象
            if (value instanceof MultipartFile) {
                MultipartFile file = (MultipartFile) value;
                //获取文件名
                value = file.getOriginalFilename();
            }

            requestParams.put(paramNames[i], value);
        }

        return requestParams;
    }

}
